import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/item_timely_consultation.dart';
import 'package:qunaimedical/components/search_bar.dart';
import 'package:qunaimedical/models/consultation.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/constants.dart';
import 'package:qunaimedical/values/urls.dart';

/// 咨询大厅（即时咨询列表）
class TimelyConsultationPublicList extends StatefulWidget {
  const TimelyConsultationPublicList({Key key}) : super(key: key);

  @override
  _TimelyConsultationPublicListState createState() =>
      _TimelyConsultationPublicListState();
}

class _TimelyConsultationPublicListState
    extends State<TimelyConsultationPublicList> {
  List<Consultation> _items = [];

  String _keyword = "";

  // 是否有下一页
  int _nextPage = 1;

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('咨询大厅'),
        elevation: 0,
      ),
      body: Column(children: [
        SearchBar(
          padding: EdgeInsets.only(left: 16, right: 16, bottom: 10),
          hintText: '输入咨询内容搜索',
          onSubmitted: (value) {
            if (value != null) {
              _keyword = value;
              _fetchData();
            }
          },
        ),
        Expanded(
          child: SmartRefresher(
            controller: _refreshController,
            enablePullDown: true,
            enablePullUp: _nextPage != 1,
            onRefresh: _fetchData,
            onLoading: _loadMore,
            child: ListView.separated(
                padding: EdgeInsets.symmetric(vertical: 10),
                itemBuilder: (c, i) => ItemTimelyConsultation(item: _items[i]),
                separatorBuilder: (c, i) => CustomDivider(),
                itemCount: _items.length),
          ),
        ),
      ]),
    );
  }

  void _fetchData() async {
    var params = {
      "pageNo": 1,
      "pageSize": Constants.limit,
      "content": _keyword,
    };
    var result = await XHttp.postJson(Urls.TIMELY_CONSULTATION_LIST, params);
    _refreshController.refreshCompleted();
    if (result != null) {
      var response = MapResponse.fromJson(result);
      if (response.code == 1) {
        if (response.data['pages'] == response.data['current']) {
          _nextPage = 1;
        } else {
          _nextPage = response.data['pages'] + 1;
        }
        var records = (response.data['records'] as List)
            .map((e) => Consultation.fromJson((e as Map<String, dynamic>)))
            .toList();
        if (mounted) {
          setState(() {
            _items = records;
          });
        }
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  void _loadMore() async {
    var params = {
      "pageNo": _nextPage,
      "pageSize": Constants.limit,
      "content": _keyword,
    };
    var result = await XHttp.postJson(Urls.TIMELY_CONSULTATION_LIST, params);
    _refreshController.loadComplete();
    if (result != null) {
      var response = MapResponse.fromJson(result);
      if (response.code == 1) {
        if (response.data['pages'] == response.data['current']) {
          _nextPage = 1;
        } else {
          _nextPage = response.data['pages'] + 1;
        }
        var records = (response.data['records'] as List)
            .map((e) => Consultation.fromJson((e as Map<String, dynamic>)))
            .toList();
        if (mounted) {
          setState(() {
            _items.addAll(records);
          });
        }
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }
}
